package com.richmond.util;

import com.richmond.gui.LockPane;
import com.richmond.gui.LockPaneController;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.EventHandler;
import javafx.scene.layout.Pane;
import org.apache.log4j.Logger;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * User: csavard
 * Date: 12-09-18
 * Time: 20:30
 */
public class JavaFxUtil {
    private static final ExecutorService executorService = new ScheduledThreadPoolExecutor(1);
    private static Logger LOGGER = Logger.getLogger(JavaFxUtil.class);

    public static void runBackgroundTask(Task task) {
        runBackgroundTask(task, null);
    }

    public static void runBackgroundTask(Task task, final Pane paneToLock) {
        if (paneToLock != null) {
            executorService.submit(new LockTask(task, paneToLock));
        }

        executorService.submit(task);
    }

    private static class LockTask implements Runnable {
        private Task task;
        private final Pane paneToLock;

        public LockTask(Task task, Pane paneToLock) {
            this.task = task;
            this.paneToLock = paneToLock;
        }

        @Override
        public void run() {
            try {
                final LockPaneController lock = LockPane.lock(paneToLock);
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        lock.text.setText(task.getTitle());
                        lock.text.textProperty().bind(task.messageProperty());
                        task.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
                            @Override
                            public void handle(WorkerStateEvent workerStateEvent) {
                                LockPane.unlock(paneToLock, lock);
                            }
                        });
                    }
                });
            } catch (Exception e) {
                LOGGER.error("Lock: " + paneToLock + " Error.", e);
            }
        }
    }
}
